package com.example.demo.controller.Document;

import com.example.demo.model.ResponseData;
import com.mongodb.client.MongoCollection;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hanqiang
 * @Classname DocumentCollectionController
 * @Date 2020/10/5 15:34
 * @Description:
 */
@RestController
@RequestMapping("/documentCollection")
public class DocumentCollectionController {
    @Autowired
    MongoTemplate mongoTemplate;

    @ApiOperation(value="获得集合，对集合进行操作插入一条数据",notes = "通过名称获得集合，向集合进行操作")
    @PostMapping("/insertCollection")
    public ResponseData insertCollection(){
        String collectionName="shops";
        MongoCollection<Document>  collection=mongoTemplate.getCollection(collectionName);
        Document document=new Document("name","橡皮").append("price","10").append("type","学习用品");
        return ResponseData.success(collection.insertOne(document));
    }

    @ApiOperation(value="获得集合，对集合中插入多条数据",notes="插入多条数据")
    @PostMapping("/insertManyCollection")
    public ResponseData insertManyCollection(){
        String collectionName="shops";
        MongoCollection<Document> collection=mongoTemplate.getCollection(collectionName);
        List<Document> documentList=new ArrayList<>();
        for(int i=0;i<5;i++){
            documentList.add(new Document("name","橡皮"+i).append("price",i+10).append("type","学习用品"));
        }
        return ResponseData.success(collection.insertMany(documentList));
    }
}
